import React from 'react'
import { Tag, Space } from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import { useLocation,useNavigate } from 'react-router-dom'
import { closeTag, setCurrentMenu } from '../../store/reducers/tab'
import './index.css'
const CommonTag = () => {
  const tabList = useSelector((state) => state.tab.tabList)
  const currentMenu = useSelector((state) => state.tab.currentMenu)
  const action = useLocation()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const perventDefault = (item, index) => {
    let length = tabList.length - 1
    dispatch(closeTag(item))
    // 关闭不是当前的tag
    if (item.path !== action.pathname) {
      return
    }
    if (index == length) {
      // 设置当前数据
      const curData = tabList[index - 1]
      dispatch(setCurrentMenu(curData))
      navigate(curData.path)
    } else {
      if (tabList.length > 1) {
        const nextData = tabList[index + 1]
        dispatch(setCurrentMenu(nextData))
        navigate(nextData.path)
      }
    }
  }
  // 点击tag事件
  const handleClick = (item, index) => {
    dispatch(setCurrentMenu(item))
    navigate(item.path)
  }
  // tag 显示
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag
        color="#55acee"
        closeIcon
        onClose={() => perventDefault(item, index)}
        key={item.name}
      >
        {item.label}
      </Tag>
    ) : (
      <Tag
        onClick={() => {
          handleClick(item, index)
        }}
        key={item.name}
      >
        {item.label}
      </Tag>
    )
  }
  return (
    <Space className="common-tag" size={[0, 8]} wrap>
      {/* <Tag color='#55acee'>首页</Tag>
      <Tag closeIcon onClose={() => perventDefault()}>
        用户列表
      </Tag> */}
      {currentMenu.name &&
        tabList.map((item, index) =>
          setTag(currentMenu.path == item.path, item, index)
        )}
    </Space>
  )
}
export default CommonTag
